import { reportEventData } from '../../dataReport/dataReportUtil'
import loginHelper from '../../pluginHelper/login'

var app = getApp()
var socketTask = null
var TAG = ''
var isConnected = false
let logger = wx.getLogManager({
  level: 1,
})

/**
 *  WebSocket创建连接
 */
function createSocket(urlStr, callback, that, intervalTimer, asTimeCounter, tag, globalData) {
  if (isConnected) {
    return
  }
  TAG = tag
  console.info(TAG, 'connectSocketUrl', urlStr)
  socketTask = wx.connectSocket({
    url: urlStr,
  })
  if (socketTask) {
    console.info(TAG, '...onOpen')
    if (!that.data.connectOk) {
      return
    }
    socketTask.onOpen((res) => {
      console.info(TAG, 'onOpen', res)
      logger.info(TAG, 'onOpen', res)
      isConnected = true
      onMessage(callback)
    })
    socketTask.onError((res) => {
      console.info(TAG, 'onError', res)
      logger.info(TAG, 'onError', res)
      isConnected = false
      socketTask = null
      let str = ''
      let type = '' //用来显示图片用的
      let errorCode = '1000001'
      if (TAG == 'paircheck1') {
        if (
          res &&
          (res.errMsg.includes('Software caused connection abort') || res.errMsg.includes('Connection timed out'))
        ) {
          errorCode = '1000033'
          // that.judgeShowWlanDialog();
        }
        str = 'sap'
        type = that.data.chooseType
      } else if (TAG == 'paircheck2') {
        str = 'app'
        type = that.data.applianceType
      }

      clearInterval(intervalTimer)
      clearTimeout(asTimeCounter)

      that.handleError(
        {
          error_code: errorCode,
          error_image_url:
            errorCode == '1000033'
              ? '/Assets/icons/HC3.0_Pairing_ConnectCheckError.png'
              : '/Assets/icons/HC3.0_Pairing_Restart.png',
        },
        {
          error_msg: JSON.stringify(res),
          des: `${str}阶段websocket报错`,
        }
      )
    })
    socketTask.onClose((res) => {
      console.info(TAG, 'onClose', res)
      logger.info(TAG, 'onClose', res)
      isConnected = false
      socketTask = null
    })
  }
}
/**
 * 通过 WebSocket 连接发送数据
 */
function sendMsg(data, callback) {
  if (socketTask && isConnected) {
    socketTask.send({
      data: JSON.stringify(data),
      success: function () {
        console.log(TAG, String('Send Request : ' + JSON.stringify(data)))
        logger.info(TAG, String('Send Request : ' + JSON.stringify(data)))
        callback()
      },
      fail: function () {},
    })
  }
}

function onMessage(callback) {
  if (socketTask) {
    socketTask.onMessage((res) => {
      console.info(TAG, 'onMessage', res.data)
      callback(res.data)
    })
  }
}
/**
 * 数据上报
 * @param {*} eventName
 * @param {*} propObj
 */
function pluginReportEventData(eventName, propObj, that) {
  let app = getApp()
  reportEventData(eventName, propObj, that)
}
/**
 * 关闭 WebSocket 连接
 */
function closeWebSocket() {
  if (socketTask) {
    socketTask.close({
      complete: function () {
        console.info(TAG, 'close ...')
      },
    })
  }
}
/**
 * 插件日志接口
 * @param {日志标签} tag
 * @param  {...any} args
 */
function pluginConsole(tag, ...args) {
  console.log('pluginConsole', tag, args)
  if (args) {
    if (args.length < 1) {
      console.error('pluginConsole', 'args is null')
    } else if (args.length < 2) {
      logger.log(tag, args[0])
    } else if (args.length < 3) {
      logger.log(tag, args[0], args[1])
    } else if (args.length < 4) {
      logger.log(tag, args[0], args[1], args[2])
    }
  }
}
/**
 * token失效，去登录
 */
function gotoLogin() {
  loginHelper.noCiamIdLogin('redirectTo')
}

function goToScanErrorPage(index) {
  wx.navigateTo({
    url: '/pages/pairing/scanerror/scanerror?result=' + app.globalData.scanErrorKeys[index],
    complete: (res) => {},
  })
}

function getStorageSync() {
  return wx.getStorageSync('showWLANPlusDialog_Key')
}

module.exports = {
  createSocket,
  sendMsg,
  onMessage,
  closeWebSocket,
  pluginReportEventData,
  pluginConsole,
  gotoLogin,
  goToScanErrorPage,
  getStorageSync,
}
